
 var activityValidationCompIds = new Array("activityType","subject","dueDate","firstName","stage","status","priority");
 var staticActivityId = '0';

 function createActivityPanel(){

        var dynamicActivityStore=CRM.commons.createStore('activityStoreid',CRM.SPComp.activityDataArray,'searchactivities/showActivitiesDynamically');
        
        var activitySearchCriteriaStore=CRM.commons.createComboStore('activitySearchCriteriaStoreid', 'activity/activitySearchCriteriaTypes');        
		
        var assignedToStore=CRM.commons.createComboStore('assignedToStoreid','activity/assignedTo','');

        var relatedToStore=CRM.commons.createComboStore('relatedToStoreid','activity/relatedToByCompanyId','');

        var relatedCompanyStore=CRM.commons.createComboStore('relatedCompanyStoreid','activity/companyNames','');

        var relatedCompanyStore=CRM.commons.createComboStore('relatedCompanyStoreid','activity/companyNames','');

        var actionStore=CRM.commons.createComboStore('actionStoreid','activity/activityReqCombo','actionTypes');        
       
        var stageStore=CRM.commons.createComboStore('stageStoreid','activity/activityReqCombo','stageTypes');

        var statusStore=CRM.commons.createComboStore('statusStoreid','activity/activityReqCombo','statusTypes');

        var priorityStore=CRM.commons.createComboStore('priorityStoreid','activity/activityReqCombo','priorityTypes');

        var opportunitiesTitleStore=CRM.commons.createComboStore('opportunitiesTitleStoreid','activity/opportunitiesTitles','');

        //Date Validation
        Ext.apply(Ext.form.VTypes, {
		daterange : function(val, field) {
			var date = field.parseDate(val);
	 
			if(!date){
				return;
			}
			if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
				var start = Ext.getCmp(field.startDateField);
				start.setMaxValue(date);
				start.validate();
				this.dateRangeMax = date;
			} 
			else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
				var end = Ext.getCmp(field.endDateField);
				end.setMinValue(date);
				end.validate();
				this.dateRangeMin = date;
			}
			return true;
		  }
	    });
        	

        var activityDetailsPanel = {
                xtype       : 'fieldset',
                id          : 'activityDetailsPanel',
                title       : 'Activity Details',
                width       : 430,
                height      : 140,
                layout      : 'form',
                labelWidth  : 120,
                items       : [
                    {
                    	xtype		: 'hidden',
                    	id			: 'activityId',
                    	fieldLabel  : 'Activity Id',
                    	value		: '0'
                    },
                    {
                    	xtype		: 'compositefield',
                    	items		: [
										{
										    xtype      	: 'combo',
										    fieldLabel 	: 'Activity Type<font color=red>*</font>',
										    id         	: 'activityType',
										    store		: actionStore,
										    displayField: 'name',
										    valueField  : 'id',
										    value		: 'SELECT',
										    triggerAction:'all',
										    width      	: 250,
										    editable 	: false,
										    listeners	: {select : function(){
										    						bindValue('activityType', 'activityTypeId');
										    					} 
										    			  }
										},
					                    {
					                    	xtype		: 'hidden',
					                    	id			: 'activityTypeId'
					                    }
                    	     		   ]
                    },
                    {
                    	xtype		: 'compositefield',
                    	items		: [
                                       {
                                           xtype      	: 'combo',
                                           fieldLabel 	: 'Assigned To',
                                           id         	: 'assignedTo',
                                           store		: assignedToStore,
                                           displayField: 'name',
                                           valueField  : 'id',
                                           value		: 'SELECT',
                                           triggerAction:'all',
                                           width      	: 250,
                                           editable	: false,
                                           listeners	: {select : function(){
                   					    						bindValue('assignedTo', 'assignedToId');
                   					    					} 
                   					    			  	}
                                       },
                                       {
                                       	xtype		: 'hidden',
                                       	id			: 'assignedToId'
                                       }
                    	     		  ]
                    },
                    {
                        xtype      : 'textfield',
                        fieldLabel : 'Subject<font color=red>*</font>',
                        id         : 'subject',
                        //value      :'Subject',
                        //allowBlank :false,
                        width      : 250
                    },
                    {
                    	xtype		: 'compositefield',
                    	items		: [
										{
										    xtype      : 'datefield',
										    fieldLabel : 'Due Date<font color=red>*</font>',
										    id         : 'dueDate',
										    vtype      : 'daterange',
										    startDateField: 'reminderDate',
										    format     : 'Y-m-d'
										},
										{	xtype		: 'displayfield', value : 'Duration: '},
										{
										    xtype      : 'textfield',
										    id         : 'duration',
										    width	   : 35,
										    value	   : '0'
										}
                    	     		   ]
                    }
                ]
            };

            var leadCustomerPanel = {
                xtype       : 'fieldset',
                id          : 'leadCustomerPanel',
                title       : 'Lead/Customer',
                width       : 450,
                height      : 140,
                layout      : 'form',
                labelWidth  : 120,
                items       : [
			                    {
			                    	xtype	   : 'hidden',
			                    	id		   : 'leadId',
			                    	fieldLabel : 'Id ',
			                    	disabled   : false
			                    },
			                    {
			                    	xtype	   : 'compositefield',
			                    	width	   : 300,
			                    	items	   : [
													{
													    xtype      	: 'textfield',
													    fieldLabel 	: 'First Name<font color=red>*</font>',
													    id         	: 'firstName',
													    width      	:  245,
													    disabled   	: true
													},
													{
														xtype		: 'button',
														text		: 'Search',
														handler		: function(){
																			showSearchWindow();
																		}
													}
			                    	     	     ]
			                    }
			                    ,
			                    {
			                        xtype      : 'textfield',
			                        fieldLabel : 'Middle Initial',
			                        id         : 'middleInitial',
			                        width      : 40,
			                        disabled   : true
			                    },
			                    {
			                        xtype      : 'textfield',
			                        fieldLabel : 'Last Name',
			                        id         : 'lastName',
			                        width      : 290,
			                        disabled   : true
			                        
			                        
			                    },
			                    {
                                    xtype     : 'compositefield',
                                    items     : [
													{
													    xtype      	: 'combo',
													    fieldLabel 	: 'Opportunity',
													    id         	: 'opportunity',
													    store		: opportunitiesTitleStore,
													    displayField: 'criteria',
													    valueField  : 'id',
													    triggerAction:'all',
													    value		: 'SELECT',	
													    //width      	: 290,
													    disabled	: true,
													    editable	: false,
													    autoLoad	: false,
													    model		: 'local',
													    lastQuery	: '',
													    listeners	: { select : function(){
													    						 bindValue('opportunity', 'opportunityId');
													    					}
													    				} 
													},
								                    {
								                    	xtype		: 'hidden',
								                    	id			: 'opportunityId'
								                    }
                                                 ]
			                    }
			                    
                ]
            };

            
            var notePanel = {
                xtype       : 'fieldset',
                title       : 'Notes',
                id          : 'notePanel',
                width       : 880,
                height      : 220,
                layout      : 'form',
                labelWidth  : 120,
                padding     : '5px',
                border      : true,
                //frame       : true,
                items       : [
                    {
                        xtype      : 'textarea',
                        fieldLabel : 'Notes',
                        id         : 'notes',
                        width      : 500,
                        height     : 75
                    },
                    {
                        xtype     : 'compositefield',
                        items     : [
										{
										    xtype      	: 'combo',
										    fieldLabel 	: 'Stage<font color=red>*</font>',
										    id         	: 'stage',
										    store		: stageStore,
										    displayField: 'name',
										    valueField  : 'id',
										    value       :'SELECT',
										    triggerAction:'all',
										    width      	:  200,
										    editable	: false,
										    listeners	: {select : function(){
										    						bindValue('stage', 'stageId');
										    					} 
										    			  }
										},
					                    {
					                    	xtype		: 'hidden',
					                    	id			: 'stageId'
					                    },
					                    {	xtype		: 'displayfield', value : 'Status<font color=red>*</font>:', width : 90},
					                    {
										    xtype      	: 'combo',
										    //fieldLabel 	: 'Status',
										    id         	: 'status',
										    store		: statusStore,
										    displayField: 'name',
										    valueField  : 'id',
										    value		: 'SELECT',
										    triggerAction:'all',
										    width      	:  200,
										    editable	: false,
										    listeners	: {select : function(){
										    						bindValue('status', 'statusId');
										    					} 
										    			  }
										},
										{
											xtype		: 'hidden',
											id			: 'statusId'
										}
                                     ]
                    },
                    
                    {
                    	xtype		: 'compositefield',
                    	items		: [
										{
										    xtype      	: 'combo',
										    fieldLabel 	: 'Priority<font color=red>*</font>',
										    id         	: 'priority',
										    store		: priorityStore,
										    displayField: 'name',
										    valueField  : 'id',
										    value		: 'SELECT',
										
										    triggerAction:'all',
										    width      	:  200,
										    editable	: false,
										    listeners	: {select : function(){
										    						bindValue('priority', 'priorityId');
										    					} 
										    			  }
										},
										{
											xtype		: 'hidden',
											id			: 'priorityId'
										}
                    	     		   ]
                    },
                    {
                    	xtype		: 'compositefield',
                    	items		: [
										{
										    xtype      : 'datefield',
										    fieldLabel : 'Reminder Date',
										    id         : 'reminderDate',
										    vtype      : 'daterange',
										    endDateField: 'dueDate',
										    format      :'Y-m-d'
										},
										{	xtype		: 'displayfield', value : 'Reminder: '},
										{
										    xtype      : 'checkbox',
										    id         : 'reminder'
										}
                    	     		   ]
                    }
                ]
            };
            

            var activityRootPanel = new Ext.Panel({
                xtype       : 'panel',
                id          : 'rootPanel',
                width       : '900',
                frame       : true,
                items       : [
			                    {
			                        xtype   : 'panel',
			                        layout  : 'hbox',
			                        items   : [leadCustomerPanel, activityDetailsPanel]
			                    },
			                    notePanel
			                    ],
                tbar        : {
			                    xtype       : 'toolbar',
			                    buttonAlign : 'right',
			                    id			: 'topToolBar',
			                    items       : [
			                        /*           
									{
									    xtype   : 'button',
									    id		: 'topNewButton',
									    text    : 'New',
									    handler : newActivityForm
									},
									'-',
									*/
									{
			                            xtype   : 'button',
			                            id		: 'topEditButton',
			                            text    : 'Edit',
			                            handler : editActivityForm
			                        },
									'-',           
			                        {
			                            xtype   : 'button',
			                            id		: 'topSaveButton',
			                            text    : 'Save',
			                            handler : function(){
			                            				validateAndSaveActivity();
			                            			}
			                        },
			                        '-',
			                        {
			                         	xtype   : 'button',
			                         	id	  	: 'topRemoveButton',
			                         	text    : 'Cancel'
			                         }
			                    ]
                },
                bbar        : {
			                    xtype       : 'toolbar',
			                    buttonAlign : 'right',
			                    id		    : 'bottomToolBar',
			                    items       : [
			                        /*           
									{
									    xtype   : 'button',
									    id		: 'newButton',
									    text    : 'New',
									    handler : newActivityForm
									},
									'-',
									*/
									{
			                            xtype   : 'button',
			                            id		: 'editButton',
			                            text    : 'Edit',
			                            handler : editActivityForm
			                        },
									'-',           
			                        {
			                            xtype   : 'button',
			                            id		: 'saveButton',
			                            text    : 'Save',
			                            handler : function(){
			                            				validateAndSaveActivity();
			                            			}
			                        },
			                        '-',
			                        {
			                        	xtype   : 'button',
			                         	id	  	: 'removeButton',
			                         	text    : 'Cancel'
			                         	//,handler : validateAndSave
			                        }
			                    ]
			                }
            });
            
            var searchTab = new Ext.Panel({
	     	    	xtype	: 'panel',
	     	    	title	: 'Search',
	     	    	//autoWidth : true,
	     	    	items	: [
								CRM.SPComp.createActivitySearchComp('spSearchActivityGridPanel', 'activitySearchCriteria', 'activityCriteriaValue', dynamicActivityStore, CRM.SPComp.createActivityColumnModel(), activitySearchCriteriaStore)
	     	    	     	  ]
	     	});
            
            var myActivityTab = new Ext.Panel({
            		xtype	: 'panel',
            		id		: 'myActivityTab',
            		title	: 'My Activity',
            		items	: [createMyActivity()]
            });

            var newActivityTab = new Ext.Panel({
        		xtype	: 'panel',
        		title	: 'New',
        		items	: [],
     	    	listeners: {activate: function(){
			 					switchForm(activityRootPanel, newActivityTab);
			 					newActivityForm();
			 				 }
 							}
            });
            var detailsTab = new Ext.Panel({
     	    	xtype	: 'panel',
     	    	id		: 'detailsTab',
     	    	title	: 'Details',
     	    	items	: [activityRootPanel],
     	    	disabled: true,
     	    	listeners: {activate: function(){
			 					if(staticActivityId != '0'){
			 						showActivityDetails(staticActivityId);
			 					}
			 					switchForm(activityRootPanel, detailsTab);
			 				 }
			 				}
     	    });
            
            var activityMainTab = new Ext.TabPanel({
        		xtype	: 'tabpanel',
        		id		: 'activityMainTab',
        		activeTab : 0,
        		height	: 550,
        		width	: '100%',
        		items	: [
        		     	    searchTab,
        		     	    //myActivityTab,
        		     	    detailsTab,
        		     	    newActivityTab
        		     	   ]
        	});
            
            
            var mainPanel = new Ext.FormPanel({
                id          : 'mainPanel',
                height      : 680,
                width       : '100%',
                frame       : false,
                items       : [activityMainTab]
            });
            
   
            validateFormOnLoad(mainPanel, activityValidationCompIds);
            return mainPanel;
 		}

 
            function validateAndSaveActivity(){
            	
               var form = Ext.getCmp('mainPanel');
               var validationSuccess = simpleFormValidation(form, activityValidationCompIds);
               if(validationSuccess == 'true'){
            	   saveActivity(); 
               }
        	 };
            
          //functions
	
            function saveActivity(){
            	var formPanel = Ext.getCmp('mainPanel');
            	var activityId = formPanel.getForm().findField('activityId').getValue();
            	var action = 'Save';
            	var message = 'No action taken!';
            	
            	if(activityId == '0'){
            		 action = 'Save';
            		 message = 'Saved Successfully!';
                 }
                if(activityId != '0'){
                	action = "Update";
              	   	message = 'Updated Successfully!';
                 }
                
     	        var values = formPanel.getForm().getValues();
     	        var data = Ext.encode(values);
     	       
         	    Ext.Ajax.request({
         		   url		: 'activity/save?action='+action,
         		   method	: 'POST',
         		   success	: function(result, request){
         			  			var jsonData = Ext.util.JSON.decode(result.responseText); 
         			  			var responsedActivityId = jsonData.data;
         			   			alert("Activity "+message);
         			   			disableActivityForm();
         			   			formPanel.getForm().findField('activityId').setValue(responsedActivityId);
         			   		  },
         		   failure 	: function(){
         			   			alert("failure");
         			   		  },
         		   jsonData : data
         	   });
         	 };
         	
         	
         	 	
				function showActivityDetails(selectedActivityId){
         		    var formPanel = Ext.getCmp('mainPanel');
         		    staticActivityId = selectedActivityId;
					formPanel.getForm().load({
					method  : 'GET',
 		            url     : 'activity/showDetails?activityId='+selectedActivityId,
 		      		success : function() {
 		      					disableActivityForm();
 		      					formPanel.findById('detailsTab').enable();
 		            		  },
 		            failure :function() { 
 		                		alert ("Failure");
 		               		  }
					});
					formPanel.findById('activityMainTab').setActiveTab('detailsTab');
				};  

				

				function reloadOpportunity(selectedLeadId){
						var form = Ext.getCmp('mainPanel').getForm();
						var oppCombo = form.findField('opportunity');
						oppCombo.setValue(null);
						oppCombo.store.removeAll();
						oppCombo.store.reload({
											params : {leadId : selectedLeadId}
											});
						form.findField('opportunity').enable();
				};

         	//Search window code 
        	var win;
        	function closeSearchWindow(){
        		win.close();
        	};
        	
        	
        	
        	function showSearchWindow(){
        	 		var leadStore=CRM.commons.createStore('leadStoreid',CRM.SPComp.leadDataArray,'searchleads/showLeadCustomer');
        	 		var leadSearchCriteriaStore=CRM.commons.createComboStore('leadSearchCriteriaStoreid', 'lead/leadSearchCriteriaTypes');
                
        			var searchLeadPanel = CRM.SPComp.createSearchComp('spSearchLeadGridPanel', 'searchCriteria', 'criteriaValue', leadStore, CRM.SPComp.createLeadColumnModel(), leadSearchCriteriaStore)
         			var searchLeadGridPanel = new Ext.getCmp('spSearchLeadGridPanel');
        			searchLeadGridPanel.getColumnModel().setHidden(12,true);
        			
        			win = new Ext.Window({
                	title		: 'Dynamic Search Window',
                	id			: 'searchWindow',
                	width		: 1170,
                	height		: 490,
                	border		: true,
                	plain		: false,
                	closable	: true,
                	collapsible : true,
                	animCollapse: true,
                	draggable 	: true,
                	maximizable : false,
                	//layout		: 'border',
                	onEsc		: true,
                	model		: true,
                	items		: [
									searchLeadPanel
                	     		  ],
                	bbar        : {
        			                    xtype       : 'toolbar',
        			                    buttonAlign : 'right',
        			                    items       : [
        			                        {
        			                            xtype   : 'button',
        			                            text    : 'OK',
        			                            handler : function(){
        			                            		   var record = Ext.getCmp('spSearchLeadGridPanel').getSelectionModel().getSelected();
        			                            		   var form = Ext.getCmp('mainPanel').getForm();
        			                            		   form.findField('leadId').setValue(record.get('id'));
        			                            		   form.findField('firstName').setValue(record.get('firstName'));
        			                            		   form.findField('middleInitial').setValue(record.get('middleInitial'));
        			                            		   form.findField('lastName').setValue(record.get('lastName'));
        			                            		   closeSearchWindow();
        			                            		   var selectedLeadId = form.findField('leadId').getValue();
        			                            		   reloadOpportunity(selectedLeadId);
        			                            		}
        			                        }
        			                    ]
        			                }     		  
         			
            		});
         			
                win.show(this);
                return win;
        	 }
        	
        	var activityCompIds = new Array(
					"opportunity","activityType","assignedTo","subject","dueDate","duration","notes","stage",
					"status","priority","reminder","reminderDate"
					);
        	
			function disableActivityForm(){
				var form = Ext.getCmp('mainPanel');
				doFormReadOnly(form, activityCompIds, true); //this method is in FormUtil.js
				
				var topButtonPanel = Ext.getCmp('topToolBar');
				var buttonPanel = Ext.getCmp('bottomToolBar');
				
				buttonPanel.findById('saveButton').disable();
				topButtonPanel.findById('topSaveButton').disable();
				
				buttonPanel.findById('editButton').enable();
				topButtonPanel.findById('topEditButton').enable();
				//applyActivityAuthorization(); //this method is in NewHeader.js
			}

			function editActivityForm(){
				var form = Ext.getCmp('mainPanel');
				doFormReadOnly(form, activityCompIds, false); //this method is in FormUtil.js
				
				var topButtonPanel = Ext.getCmp('topToolBar');
				var buttonPanel = Ext.getCmp('bottomToolBar');
				
				buttonPanel.findById('editButton').disable();
				topButtonPanel.findById('topEditButton').disable();
				
				buttonPanel.findById('saveButton').enable();
				topButtonPanel.findById('topSaveButton').enable();
				//buttonPanel.findById('saveButton').setText('Update');	
				//topButtonPanel.findById('topSaveButton').setText('Update');
			};
			
			function newActivityForm(){
				editActivityForm();
				var form = Ext.getCmp('mainPanel');
				var topButtonPanel = Ext.getCmp('topToolBar');
				var buttonPanel = Ext.getCmp('bottomToolBar');
				
				form.getForm().reset();

				buttonPanel.findById('saveButton').setText('Save');
				buttonPanel.findById('saveButton').enable();
				buttonPanel.findById('editButton').disable();
				
				topButtonPanel.findById('topSaveButton').setText('Save');
				topButtonPanel.findById('topSaveButton').enable();						
				topButtonPanel.findById('topEditButton').disable();
				//applyActivityAuthorization();//this method is in NewHeader.js
			};
			

			//delete grid data function by Rachna
			function showActivityList(){
				var grid = Ext.getCmp('spSearchActivityGridPanel');
				grid.store.removeAll();
				grid.store.reload();
			   }

			function deleteDetails(){
	   			var record = Ext.getCmp('spSearchActivityGridPanel').getSelectionModel().getSelected();
	    		    var selectedActivityId = record.get('id');
	    		    Ext.Ajax.request({
	   			    method  : 'POST',
	   	            url     :  'activity/deleteActivityDetail?activityId='+selectedActivityId,
	   	      		success : function() {
	   				          	showActivityList();
	   	            		  },
	   	            failure	:function() { 
	   	                		alert('Failure!');
	   	               		  }
	   			});
	   		}
	   		
	   		function showMessage(){
	   			 Ext.MessageBox.show({
	         	            title	: 'Confirm',
	         	            msg		: 'Are you sure you want to delete this records:',
	         	            width	:200,
	         	            buttons	: Ext.MessageBox.OKCANCEL,
	         	            multiline: false,
	         	            fn		: function(btn, text) {
			         	            	if (btn == 'ok') {
			         	            		deleteDetails();
			         	            	   }
	         	            	}
	         	           });
	   		}
   		
